<?php

class Quad_File {

	public function __construct($path) {
		$this->path = realpath($path);
	}
	
	public function create($path) {
		if ($path instanceof self) {
			return $path;
		}
		return new self($path);
	}
	
	public function concat($path) {}
	
	public function isWithin($path) {
		$child = self::create($path);
		$check = $this->path;
		do {			
			if ($check == $child->path) {				
				return true;
			}
		} while (($check = dirname($check)));
		
		return false;
	}
	
	/**
	 * Get a list of filenames in the given directory
	 *
	 * @param bool $recurse  If true, recurse into subdirectories
	 * @param string/callback $ext  If a string, the file extension which to include; if a callable function, the filter function
	 * @return array
	 */
	public function ls($recurse = true, $ext = false) {
		$this->path = $this->path;
		$files = array();
		try {
			$fileCollection = new DirectoryIterator($this->path);
			foreach ($fileCollection as $file) {
				if (
					!$file->isDot() &&
					substr($file->getFilename(),0,1) != '.' && (              // ignore . and .. and hidden files such as .svn and .htaccess
						$ext === false ||                                       // no $ext filter
						(is_callable($ext) && $ext($file)) ||                   // $ext filter is a function that returns true
						substr($file->getFilename(), -1 * strlen($ext)) == $ext // $ext filter is a string file extension
					)
				) {
					if ($file->isDir() && $recurse) {
						// we have a dir and we want to recurse
						$files = array_merge($files, self::create($this->path . '/' . $file->getFilename())->ls($recurse, $ext));
						
					} elseif ($file->isFile()) {				
						// we have a file: add it to the list
						$files[] = $this->path . '/' . $file->getFilename();
					}
				}
			}
		} catch(Exception $e) {
			throw $e;
		}
		return $files;
	}
	
}

